package com.ssca.mybatis;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.postgresql.util.PSQLException;

import com.ssca.redis.IntentData;
import com.ssca.redis.JedisUtil;
import com.ssca.redis.PopResultFromRedis;


public class InsertAliases {

	public static void main(String[] args) {
		new InsertAliases().insert();
	}


	public void insert(){

		Reader reader;
		try {
			reader = Resources.getResourceAsReader("MybatisConfig.xml");
			SqlSessionFactoryBuilder ssfBuilder = new SqlSessionFactoryBuilder();  
			SqlSessionFactory sqlSessionFactory = ssfBuilder.build(reader);  
			SqlSession sqlSession = sqlSessionFactory.openSession();
			AliasesDAO aliasesDAO = sqlSession.getMapper(AliasesDAO.class);

			PopResultFromRedis popResult = new PopResultFromRedis();
			while(JedisUtil.llen("intent")!=0){
				try{
					IntentData intentData = popResult.popIntentData();
					//调用aliseseDAO的方法就可以执行sql语句
					//sourceInfo
					Integer sourceId = aliasesDAO.findComponentId(intentData.getSourcePkg(), intentData.getSourceClass());
					//				System.out.println("source:"+sourceId);
					if(sourceId!=null){//avoid the sourceId is null
						//targetInfo
						if(intentData.getDesPkg().equals("")){//检测报告缺少desPkg字段
							//判断desClass在SourcePkg里面是否存在，如果存在，则desPkg默认是sourcePkg
							Integer targetId = aliasesDAO.findComponentId(intentData.getSourcePkg(), intentData.getDesClass());
							if(targetId==null){
								//若不存在，则把所有的匹配的添加到Aliases
								List<Integer> targetAllResult = aliasesDAO.findTargetIdIgnorePkg(intentData.getDesClass());
								if(targetAllResult!=null&&targetAllResult.size()>0){
									//insert
									for(int i:targetAllResult)
										aliasesDAO.insertIntoAliases(sourceId, i);
								}
							}else{
								//insert
								aliasesDAO.insertIntoAliases(sourceId, targetId);
							}


						}else{//检测报告有desPkg字段信息
							int targetId = aliasesDAO.findComponentId(intentData.getDesPkg(), intentData.getDesClass());
							//insert
							aliasesDAO.insertIntoAliases(sourceId, targetId);
						}	
					}
					sqlSession.commit();
				}catch (Exception e){
					e.printStackTrace();
					sqlSession.rollback();
					System.out.println("exist!");
				}
			}

		}catch (Exception e) {
			e.printStackTrace();
		}  

	}
}
